﻿
namespace MyFurion.Application
{
    /// <summary>
    /// 角色菜单权限仓储
    /// </summary>
    public class RoleMenuRepository : BaseRepository<RoleMenuInfo>,ITransient
    {
        /// <summary>
        /// 授权角色菜单
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="grantMenus">菜单id</param>
        /// <returns></returns>
        public async Task<bool> GrantMenu(long roleId, List<long> grantMenus)
        {
            bool result = true;
            List<long> oldIds = await Context.Queryable<RoleMenuInfo>().Where(p => p.RoleId == roleId).Select(p => p.Id).ToListAsync();
            //插入数据
            if (grantMenus.Any())
            {
                var roles = grantMenus.Select(u => new RoleMenuInfo
                {
                    RoleId = roleId,
                    MenuId=u
                }).ToList();
                result=await Insert(roles);
            }
            //删除原有关联菜单
            if (result)
            {
                if (oldIds.Any())
                {
                    await DeleteByWhere(p => oldIds.Contains(p.Id), true);
                }
            }
            return result;
        }
        /// <summary>
        /// 获取角色的菜单Id集合
        /// </summary>
        /// <param name="roleIdList"></param>
        /// <returns></returns>
        public async Task<List<long>> GetRoleMenuIdList(List<long> roleIdList)
        {
            return await Context.Queryable<RoleMenuInfo>().Where(p => roleIdList.Contains(p.RoleId)).Select(p => p.MenuId).Distinct().ToListAsync();
        }
    }
}
